﻿// <summary>
// ----------------------------------------------------------------------------------------------------------------------
// 解决方案：Nuctech.ACCT.OIS.DataAccess
// 项目：Nuctech.ACCT.OIS.DataAccess.Impl
// 文件名称：DataAccessManagerImpl.cs
// ----------------------------------------------------------------------------------------------------------------------
// 功能描述：数据库管理
// 创建者：zhangwentao
// 版本：
// 创建日期：2022-10-09 15:40

using Dapper;
using DapperExtensions.Sql;
using Microsoft.Extensions.Logging;
using static DAL.Enum;

namespace DAL.DataProcess;

public class DataAccessManagerImpl : IDataAccessManager
{
    private string _connectionStr;
    private string _connectionBasicStr;
    private string _connectionCodeStr;
    private string _connectionImageStr;
    private string _connectionEventStr;
    private string _connectionPreviewStr;

    private DatabaseTypeEnum _databaseType;
    private DatabaseEnvironmentEnum _databaseEnvironment;
    private readonly ILogger<DataAccessManagerImpl> _logger;

    public DataAccessManagerImpl(ILogger<DataAccessManagerImpl> logger)
    {
        _logger = logger;
        Initialize();
    }

    public smErrorCode Initialize()
    {
        try
        {
            _databaseEnvironment = DatabaseEnvironmentEnum.Development;

            _databaseType = DatabaseTypeEnum.NpgSQL;

            switch (_databaseType)
            {
                case DatabaseTypeEnum.NpgSQL:
                    if (_databaseEnvironment == DatabaseEnvironmentEnum.Development)
                    {
                        // _connectionStr = ConfigHelper.GetConnectionStringDev;

                        _connectionBasicStr = "host = 127.0.0.1; port = 5433; database = basicinfo; username = postgres; password = root#123; pooling = true";

                        _connectionCodeStr = "host = 127.0.0.1; port = 5433; database = codeinfo;  username = postgres; password = root#123; pooling = true";

                        _connectionEventStr = "host = 127.0.0.1; port = 5433; database = eventinfo; username = postgres; password = root#123; pooling = true";

                        _connectionImageStr = "host = 127.0.0.1; port = 5433; database = imageinfo; username = postgres; password = root#123; pooling = true";

                        _connectionPreviewStr = "host = 127.0.0.1; port = 5433; database = previewinfo; username = postgres; password = root#123; pooling = true";
                    }
                    else
                    {
                        throw new CustomException($"软件运行环境'{_databaseEnvironment}'不存在", new ArgumentOutOfRangeException(), smErrorCode.sm_ec_OutOfSpace);
                    }
                    break;

                default:
                    throw new CustomException($"数据库类型'{_databaseType}'不存在", new ArgumentOutOfRangeException(), smErrorCode.sm_ec_OutOfSpace);
            }

            DapperExtensions.DapperExtensions.SqlDialect = new PostgreSqlDialect();

            return smErrorCode.sm_ec_Success;
        }
        catch (Exception e)
        {
            smErrorCode errorCode = e is CustomException ? (e as CustomException).ErrorCode : smErrorCode.sm_ec_Failure;
            _logger.LogError($"[Initialize][数据库管理初始化][{errorCode:X}--{errorCode}]\r\n[{e.Message}\r\n{e.StackTrace}\r\n]");
            throw new CustomException(e.Message, e, errorCode);
        }
    }

    public smErrorCode Start()
    {
        return smErrorCode.sm_ec_Success;
    }

    public smErrorCode Stop()
    {
        return smErrorCode.sm_ec_Success;
    }

    public IDataAccess GetDataAccess(DatabaseChildrenTypeEnum dbChildrenType)
    {
        string str = string.Empty;

        IDataAccess dataAccess = null;

        switch (_databaseType)
        {
            case DatabaseTypeEnum.NpgSQL:

                switch (dbChildrenType)
                {
                    case DatabaseChildrenTypeEnum.DbInfo:
                        str = _connectionStr;
                        break;

                    case DatabaseChildrenTypeEnum.BasicInfo:
                        str = _connectionBasicStr;
                        break;

                    case DatabaseChildrenTypeEnum.CodeInfo:
                        str = _connectionCodeStr;
                        break;

                    case DatabaseChildrenTypeEnum.EventInfo:
                        str = _connectionEventStr;
                        break;

                    case DatabaseChildrenTypeEnum.ImageInfo:
                        str = _connectionImageStr;
                        break;

                    case DatabaseChildrenTypeEnum.PreviewInfo:
                        str = _connectionPreviewStr;
                        break;

                    default:
                        throw new CustomException($"数据库类型'{dbChildrenType}'不存在", new ArgumentOutOfRangeException(), smErrorCode.sm_ec_OutOfSpace);
                }
                break;

            default:
                throw new CustomException($"数据库类型'{dbChildrenType}'不存在", new ArgumentOutOfRangeException(), smErrorCode.sm_ec_OutOfSpace);
        }

        if (string.IsNullOrWhiteSpace(str))
        {
            throw new CustomException($"数据库连接字符串为空", new Exception());
        }

        dataAccess = Activator.CreateInstance<DataAccessImpl>();
        dataAccess.Initialize(str);
        SimpleCRUD.SetDialect(SimpleCRUD.Dialect.PostgreSQL);

        return dataAccess;
    }
}